import $store from '@/store/index.js';


function replaceEmojis(text,size = '15px') {
  const emojiList = $store.state.common.emojis
  let nodes = [];
  let cursor = 0;
  const nameRegex = /{([^:]+):([^}]+)}/g;
  // const nameRegex = /{([^:]+):(\d+)}/g;

  while (cursor < text.length) {
    let match = null;
    let emoji = null;
    let nameMatch = null;
	
    // Find the first matching emoji in the remaining text
    for (let i = 0; i < emojiList.length; i++) {
      const regex = new RegExp(escapeRegExp(emojiList[i].regName), 'g');
      regex.lastIndex = cursor;  // Reset regex search position
      const tempMatch = regex.exec(text);
      if (tempMatch && (!match || tempMatch.index < match.index)) {
        match = tempMatch;
        emoji = emojiList[i];
      }
    }

    // Find the first occurrence of the custom pattern <张三:5>
    nameRegex.lastIndex = cursor; // Reset regex search position
    const tempNameMatch = nameRegex.exec(text);
    if (tempNameMatch && (!match || tempNameMatch.index < match.index)) {
      nameMatch = tempNameMatch;
    }

    // Determine the next index to process
    let nextIndex = text.length;
    if (nameMatch && nameMatch.index < nextIndex) {
      nextIndex = nameMatch.index;
    }
    if (match && match.index < nextIndex) {
      nextIndex = match.index;
    }

    // Process the text up to the next match
    if (cursor < nextIndex) {
      nodes.push({
        type: 'text',
        text: text.substring(cursor, nextIndex)
      });
      cursor = nextIndex;
    }

    // Replace the name match or the emoji match
    if (nameMatch && nextIndex === nameMatch.index) {
		nodes.push({
			name: 'a',
			attrs: {
			  style: 'color: #0075ce;' // Add color style here
			},
			atid:`${nameMatch[2]}`,
			atname:`${nameMatch[1]}`,
			children: [{
			  type: 'text',
			  text: `@${nameMatch[1]} `
			}]
		});
      cursor += nameMatch[0].length;
    } else if (match && nextIndex === match.index) {
      nodes.push({
        name: 'img',
        attrs: {
          src: emoji.src,
          width: size,
          height: size,
          style: 'margin-left: 1px; margin-right: 1px; margin-top: -5px; vertical-align: middle;'
        }
      });
      cursor += match[0].length;
    }
  }

  return [{
    name: 'div',
    attrs: {
      class: 'msgText-class',
    },
    children: nodes
  }];
}

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

export {
  replaceEmojis
}
